logUtil = require('../lib/log');
module.exports = {
    // 模块介绍
    summary: 'my customized rule for AnyProxy',

    // 发送请求前拦截处理
    * beforeSendRequest(requestDetail) {
        /* ... */
    },
    // 发送响应前处理
    * beforeSendResponse(requestDetail, responseDetail) {
        var postUrl = "127.0.0.1"
        if (requestDetail.url.indexOf("profile_ext?action=home") >= 0) { //当链接地址为公众号历史消息页面时(第二种页面形式)
            var body = responseDetail.response.body;
			logUtil.printLog("公众号HTML页面");
            try {
                var reg = /var msgList = \'(.*?)\';/; //定义历史消息正则匹配规则（和第一种页面形式的正则不同）
                var ret = reg.exec(body.toString()); //转换变量为string
				var list = ret[1];
				var replace1 = list.replace(/&quot;/g,"");
				var replace2 = replace1.replace(/&nbsp;/g,"");
				var replace3 = replace2.replace(/,digest:/g,"");
				var replace4 = replace3.replace(/\\/g,"");
				var replace5 = replace4.replace(/amp;/g,"");
				var replace6 = replace5.replace(/amp;/g,"");
				var url_list = replace6.match(/content_url:(.*?),/g)
				for(var i=0;i<url_list.length;i++)
				{
					url_list[i]=url_list[i].slice(12,-1)
				}
				var url_map = {};
				url_map["url_list"]= url_list;
                HttpPost(JSON.stringify(url_map),postUrl,"/wechat/postlist");//这个函数是后文定义的，将匹配到的历史消息json发送到自己的服务器
            } catch(e) {
                logUtil.printLog(e);
            }
        } else if (requestDetail.url.indexOf("profile_ext?action=getmsg") >= 0) { //第二种页面表现形式的向下翻页后的json
            var body = responseDetail.response.body ;
			logUtil.printLog("公众号JSON页面") 
			try {
				var replace1 = body.toString().replace(/\\/g,"");
				var replace2 = replace1.replace(/amp;/g,"");
				var url_list = replace2.match(/content_url(.*?),/g)
				for(var i=0;i<url_list.length;i++)
				{
					url_list[i]=url_list[i].slice(14,-2);
				}
				var url_map = {};
				url_map["url_list"]= url_list;
				HttpPost(JSON.stringify(url_map),postUrl,"/wechat/postlist");
            } catch(e) {
                logUtil.printLog(e);
            }
        }
        return {
            response: responseDetail.response
        };
    },
    // 是否处理https请求
    * beforeDealHttpsRequest(requestDetail) {
        return {
            request: requestDetail.request
        };
    },
    // 请求出错的事件
    * onError(requestDetail, error) {
        /* ... */
    },
    // https连接服务器出错
    * onConnectError(requestDetail, error) {
        /* ... */
    }
};
function HttpPost(data, url, path) { //将json发送到服务器，str为json内容，url为历史消息页面地址，path是接收程序的路径和文件名
    var http = require('http');
    var options = {
        method: "POST",
        host: url,
        port: 8080,
        path: path,
        headers: {
            'Content-Type': 'application/json',
            "Content-Length": data.length
        }
    };
	
    var req = http.request(options, function (res) {
        res.setEncoding('utf8');
        res.on('data', function (chunk) {
            console.log('BODY: ' + chunk);
		});
	});
    req.on('error', function (e) {
        console.log('problem with request: ' + e.message);
    });
    req.write(data);
    req.end();
}
